package com.speechb.modules.system.admin.controller;

import com.speechb.common.codec.Md5Utils;
import com.speechb.modules.system.admin.controller.base.BaseController;
import com.speechb.modules.system.admin.entity.SysUser;
import com.speechb.modules.system.admin.service.ISysUserService;
import com.speechb.modules.utils.UserUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author : llj
 * @version :2.1.0
 * @date : 2019/10/3 7:34
 */
@RestController
@RequestMapping("${adminRoot}/sys_user")
public class SysUserController extends BaseController {
    private final static Logger LOGGER = LoggerFactory.getLogger(SysMenuController.class);
    @Autowired
    ISysUserService sysUserService;

    @PutMapping("/change_pwd")
    public void changePassword() {
        String originPassword = getPara("origin_password");
        String newPassword = getPara("new_password");
        String captcha = getPara("captcha");

        String code = (String) getSession().getAttribute("admin_change_password_captcha_code");
        String username = (String) UserUtil.getSubject().getPrincipal();
        if(!StringUtils.equalsIgnoreCase(captcha, code)) {
            // 激活码不正确
            LOGGER.warn("[changePassword]Incorrect activation code，username is {}, code is {}", username, captcha);
            renderFail();
            return;
        }
        LOGGER.warn("[changePassword]System user changes password，username is {}", username);
        String password = sysUserService.findPassword(username);
        String userPwd = Md5Utils.md5(originPassword,2);
        if (!StringUtils.equals(password, userPwd)) {
            LOGGER.warn("[changePassword]Failed to change password, password does not match");
            renderFail();
            return;
        }
        SysUser sysUser = new SysUser();
        sysUser.setUsername(username);
        sysUser.setPassword( Md5Utils.md5(newPassword,2));
        sysUserService.updateSysUser(sysUser);
        renderSuccess();
    }
}
